// 使用后端 API 进行转换

// DOM 元素引用
const curlInput = document.getElementById('curl-input');
const languageSelect = document.getElementById('language-select');
const codeOutput = document.getElementById('code-output');
const convertBtn = document.getElementById('convert-btn');
const copyBtn = document.getElementById('copy-btn');

// 语言映射配置
const languageMap = {
    'python': { func: 'toPython', name: 'Python' },
    'javascript': { func: 'toJavaScript', name: 'JavaScript' },
    'node': { func: 'toNodejs', name: 'Node.js' },
    'go': { func: 'toGo', name: 'Go' },
    'java': { func: 'toJava', name: 'Java' },
    'php': { func: 'toPhp', name: 'PHP' },
    'csharp': { func: 'toCsharp', name: 'C#' },
    'ruby': { func: 'toRuby', name: 'Ruby' },
    'rust': { func: 'toRust', name: 'Rust' },
    'swift': { func: 'toSwift', name: 'Swift' },
    'kotlin': { func: 'toKotlin', name: 'Kotlin' },
    'dart': { func: 'toDart', name: 'Dart' },
    'r': { func: 'toR', name: 'R' },
    'powershell': { func: 'toPowershell', name: 'PowerShell' },
    'http': { func: 'toHttp', name: 'HTTP' },
    'wget': { func: 'toWget', name: 'Wget' }
};

// 转换状态管理
let isConverting = false;
let autoConvertTimeout = null;

/**
 * 初始化应用程序
 */
function initApp() {
    // 绑定事件监听器
    curlInput.addEventListener('input', handleInputChange);
    languageSelect.addEventListener('change', handleLanguageChange);
    convertBtn.addEventListener('click', handleConvertClick);
    copyBtn.addEventListener('click', handleCopyClick);
    
    // 初始化复制按钮状态
    updateCopyButtonState();
    
    console.log('cURL转代码工具已初始化');
}

/**
 * 处理输入框内容变化
 */
function handleInputChange() {
    // 清除之前的自动转换定时器
    if (autoConvertTimeout) {
        clearTimeout(autoConvertTimeout);
    }
    
    // 设置新的自动转换定时器（防抖）
    autoConvertTimeout = setTimeout(() => {
        const inputText = curlInput.value.trim();
        if (inputText) {
            convertCurlCommand();
        } else {
            clearOutput();
        }
    }, 500); // 500ms 防抖延迟
}

/**
 * 处理语言选择变化
 */
function handleLanguageChange() {
    const inputText = curlInput.value.trim();
    if (inputText) {
        convertCurlCommand();
    }
}

/**
 * 处理转换按钮点击
 */
function handleConvertClick() {
    const inputText = curlInput.value.trim();
    if (!inputText) {
        showError('请输入 cURL 命令');
        return;
    }
    
    convertCurlCommand();
}

/**
 * 处理复制按钮点击
 */
async function handleCopyClick() {
    const outputText = codeOutput.textContent.trim();
    
    if (!outputText || outputText.includes('在左侧输入') || outputText.includes('错误')) {
        showError('没有可复制的代码内容');
        return;
    }
    
    try {
        await navigator.clipboard.writeText(outputText);
        showCopySuccess();
    } catch (error) {
        console.error('复制失败:', error);
        
        // 降级方案：使用传统的选择和复制方法
        try {
            const textArea = document.createElement('textarea');
            textArea.value = outputText;
            document.body.appendChild(textArea);
            textArea.select();
            document.execCommand('copy');
            document.body.removeChild(textArea);
            showCopySuccess();
        } catch (fallbackError) {
            showError('复制失败，请手动选择复制');
        }
    }
}

/**
 * 转换 cURL 命令
 */
async function convertCurlCommand() {
    if (isConverting) return;
    
    const inputText = curlInput.value.trim();
    const selectedLanguage = languageSelect.value;
    
    if (!inputText) {
        clearOutput();
        return;
    }
    
    // 设置转换状态
    setConvertingState(true);
    
    try {
        const languageConfig = languageMap[selectedLanguage];
        if (!languageConfig) {
            throw new Error(`不支持的语言: ${selectedLanguage}`);
        }
        
        // 调用后端 API
        const response = await fetch('/api/convert', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                curlCommand: inputText,
                language: selectedLanguage
            })
        });
        
        const result = await response.json();
        
        if (!response.ok) {
            throw new Error(result.error || '转换请求失败');
        }
        
        if (result.success) {
            displayResult(result.code, languageConfig.name);
        } else {
            throw new Error(result.error || '转换失败');
        }
        
    } catch (error) {
        console.error('转换错误:', error);
        showError(`转换失败: ${error.message}`);
    } finally {
        setConvertingState(false);
    }
}

/**
 * 显示转换结果
 */
function displayResult(code, languageName) {
    if (!code || code.trim() === '') {
        showError('转换结果为空，请检查 cURL 命令格式');
        return;
    }
    
    codeOutput.textContent = code;
    codeOutput.style.color = 'var(--text-primary)';
    updateCopyButtonState();
    
    // 添加成功动画效果
    codeOutput.style.animation = 'fadeIn 0.3s ease-out';
    setTimeout(() => {
        codeOutput.style.animation = '';
    }, 300);
}

/**
 * 显示错误信息
 */
function showError(message) {
    codeOutput.textContent = `❌ ${message}`;
    codeOutput.style.color = '#ef4444';
    updateCopyButtonState();
    
    // 如果是空输入，3秒后恢复默认状态
    if (message.includes('请输入')) {
        setTimeout(() => {
            if (codeOutput.textContent.includes('请输入')) {
                clearOutput();
            }
        }, 3000);
    }
}

/**
 * 清空输出
 */
function clearOutput() {
    codeOutput.textContent = '在左侧输入 cURL 命令并选择目标语言，代码将自动生成在这里...';
    codeOutput.style.color = 'var(--text-muted)';
    updateCopyButtonState();
}

/**
 * 设置转换状态
 */
function setConvertingState(converting) {
    isConverting = converting;
    
    if (converting) {
        convertBtn.disabled = true;
        convertBtn.innerHTML = '<span class="btn-icon">⏳</span>转换中...';
        codeOutput.textContent = '正在转换中，请稍候...';
        codeOutput.style.color = 'var(--text-muted)';
    } else {
        convertBtn.disabled = false;
        convertBtn.innerHTML = '<span class="btn-icon">🔄</span>转换代码';
    }
    
    updateCopyButtonState();
}

/**
 * 更新复制按钮状态
 */
function updateCopyButtonState() {
    const outputText = codeOutput.textContent.trim();
    const hasValidOutput = outputText && 
                          !outputText.includes('在左侧输入') && 
                          !outputText.includes('正在转换') && 
                          !outputText.includes('❌') &&
                          !isConverting;
    
    copyBtn.disabled = !hasValidOutput;
    
    if (hasValidOutput) {
        copyBtn.style.opacity = '1';
        copyBtn.style.cursor = 'pointer';
    } else {
        copyBtn.style.opacity = '0.5';
        copyBtn.style.cursor = 'not-allowed';
    }
}

/**
 * 显示复制成功状态
 */
function showCopySuccess() {
    const originalText = copyBtn.innerHTML;
    const originalClass = copyBtn.className;
    
    // 设置复制成功状态
    copyBtn.innerHTML = '<span class="btn-icon">✅</span>已复制';
    copyBtn.classList.add('copy-success');
    copyBtn.disabled = true; // 防止重复点击
    
    // 2秒后恢复初始状态
    setTimeout(() => {
        copyBtn.innerHTML = originalText;
        copyBtn.className = originalClass;
        copyBtn.disabled = false;
        // 重新更新按钮状态以确保正确性
        updateCopyButtonState();
    }, 2000);
}

// 在页面加载完成后初始化应用
document.addEventListener('DOMContentLoaded', initApp);

// 导出函数供调试使用
window.curlConverterApp = {
    convertCurlCommand,
    clearOutput,
    languageMap
};